package com.cd.order.api.impl;

import com.cd.common.exception.LqqException;
import com.cd.order.api.OrderService;
import com.cd.order.dto.CameraOrderDto;
import com.cd.order.jpa.domain.CameraOrder;
import com.cd.order.jpa.domain.OrderRecord;
import com.cd.order.jpa.repo.CameraOrderRepository;
import com.cd.order.jpa.repo.OrderRecordRepository;
import com.cd.schedule.api.CalenderService;
import com.cd.schedule.jpa.domain.ScheduleEntity;
import com.cd.schedule.jpa.repo.ScheduleEntityRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CameraOrderRepository orderRepo;

    @Autowired
    private OrderRecordRepository recordRepo;

    @Autowired
    private CalenderService calenderService;
    @Autowired
    private ScheduleEntityRepo scheduleEntityRepo;

    @Override
    public List<CameraOrder> getAllOrder() {
        return orderRepo.findAll();
    }

    @Override
    public void addOrder(CameraOrderDto cameraOrder) {
        if (cameraOrder.getOrderId() != null){
            throw new LqqException("非法订单");
        }
        cameraOrder.setCreateTime(new Date());
        //添加订单时，同步添加日程 逻辑做到前端？
        ScheduleEntity schedule = validateAndCreateSchedule(cameraOrder);
        ScheduleEntity schedule1 = calenderService.modifySchedules(schedule);
        cameraOrder.setLinkSchedule(schedule1.getId());
        orderRepo.save(CameraOrderDto.buildCameraOrder(cameraOrder));
    }

    @Override
    public void updateOrder(CameraOrderDto cameraOrder) {
        if (cameraOrder.getOrderId() == null){
            throw new LqqException("非法订单");
        }
        //添加订单时，同步添加日程 逻辑做到前端？
        //ScheduleEntity schedule = validateAndCreateUpdateSchedule(cameraOrder);
        ScheduleEntity schedule1 = calenderService.modifySchedules(cameraOrder.getSchedule());
        cameraOrder.setLinkSchedule(schedule1.getId());
        orderRepo.save(CameraOrderDto.buildCameraOrder(cameraOrder));
    }

    @Override
    public List<OrderRecord> getOrderRecord(Long orderId) {
        return recordRepo.findByOrderId(orderId);
    }
    //校验并同步日程
    public ScheduleEntity validateAndCreateSchedule(CameraOrderDto cameraOrderDto) {
        ScheduleEntity schedule = cameraOrderDto.getSchedule();
        schedule.setTitle(cameraOrderDto.getCosName() + "-" +
                cameraOrderDto.getCustomerName() + "-" +
                cameraOrderDto.getCustomerRemark());//角色+用户名+联系 v/q
        schedule.setScheduleId(null); // 新增时ID可设为null，由数据库生成，或使用UUID

        return schedule;
    }

}
